package homework.server.worker;

import homework.server.IOStream;
import homework.server.terminal.Command;
import homework.server.terminal.Terminal;

import java.io.Closeable;
import java.io.IOException;
import java.net.Socket;
import java.util.Map;

public class TerminalWorker implements Runnable, Closeable {
    private Socket client;
    private Terminal terminal;

    private IOStream ioStream;

    public TerminalWorker(Socket cli, Map<String, String> global, Map<String, Command> cmds) throws IOException {
        this.client = cli;
        try {
            ioStream = new IOStream(client);
        } catch (IOException e) {
            close();
            throw e;
        }
        terminal = new Terminal(ioStream, global, cmds);
    }

    @Override
    public void run() {
        while (!ioStream.isSocketClosed() && !terminal.isClosed()) {
            String line = null;
            try {
                line = ioStream.readLine();
            } catch (IOException e) {
                e.printStackTrace();
                break;
            }
            line = line.trim();
            if(line.isEmpty()) continue;

            String[] cmdArgs = line.split("\\s+", 2);
            try {
                // XXX: 参数字符串应该在Terminal中解析分割
                int code = terminal.execute(cmdArgs[0], cmdArgs.length == 1 ? null : cmdArgs[1].split(" "));
                terminal.setVariable("?", String.valueOf(code));
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        try {
            close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void close() throws IOException {
        ioStream.close();
        if(terminal != null) terminal.close();
    }
}
